<template>
    <div class="banner-list-container">
        <!-- 搜索区域 -->
        <el-form inline class="search-form">
            <el-form-item label="标题">
                <el-input v-model="searchParams.title" placeholder="请输入标题" clearable
                    @clear="fetchBannerData"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="fetchBannerData">搜索</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="handleAdd">新增轮播图</el-button>
            </el-form-item>
        </el-form>

        <!-- 轮播图列表表格 -->
        <el-table :data="filteredBannerList" border style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
            <el-table-column prop="title" label="标题" width="200" align="center"></el-table-column>
            <el-table-column prop="url" label="图片" width="200" align="center">
                <template slot-scope="scope">
                    <img :src="scope.row.url" alt="轮播图" style="width: 100px; height: auto" />
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="text" class="delete-btn"
                        @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total"></el-pagination>

        <!-- 新增轮播图信息的对话框 -->
        <el-dialog title="新增轮播图信息" :visible.sync="addDialogVisible" width="50%">
            <el-form :model="addForm" label-width="100px" ref="addForm" :rules="addFormRules">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="addForm.title"></el-input>
                </el-form-item>
                <el-form-item label="上传图片" prop="file">
                    <el-upload class="upload-demo" action="http://localhost:10010/admin/common/upload"
                        :headers="{ token: user.token }" :on-success="handleUploadSuccess" :on-error="handleUploadError"
                        :before-upload="beforeUpload" :file-list="fileList" list-type="picture-card" :limit="1"
                        :on-exceed="handleExceed" :on-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAdd">确定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑轮播图信息的对话框 -->
        <el-dialog title="编辑轮播图信息" :visible.sync="editDialogVisible" width="50%">
            <el-form :model="editForm" label-width="100px" ref="editForm" :rules="editFormRules">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="editForm.title"></el-input>
                </el-form-item>
                <el-form-item label="上传图片" prop="file">
                    <el-upload class="upload-demo" action="http://localhost:10010/admin/common/upload"
                        :headers="{ token: user.token }" :on-success="handleEditUploadSuccess"
                        :on-error="handleUploadError" :before-upload="beforeUpload" :file-list="fileList"
                        list-type="picture-card" :limit="1" :on-exceed="handleExceed" :on-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitEdit">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import request from '@/utils/request';
export default {
    data() {
        return {
            user: JSON.parse(localStorage.getItem('user') || '{}'),
            searchParams: {
                title: "",
                page: 1,
                pageSize: 10,
            },
            bannerList: [],
            total: 0,
            currentPage: 1,
            pageSize: 10,
            loading: false,
            addDialogVisible: false,
            editDialogVisible: false,
            addForm: {
                title: "",
                url: "",
                file: null,
            },
            editForm: {
                id: null,
                title: "",
                url: "",
                file: null,
            },
            addFormRules: {
                title: [{ required: true, message: "请输入标题", trigger: "blur" }],
                file: [{ required: true, message: "请上传图片", trigger: "change" }],
            },
            editFormRules: {
                title: [{ required: true, message: "请输入标题", trigger: "blur" }],
            },
            fileList: [],
        };
    },
    computed: {
        // 过滤掉 delFlag 为 1 的数据
        filteredBannerList() {
            return this.bannerList.filter((item) => item.delFlag === 0);
        },
    },
    created() {
        this.fetchBannerData();
    },
    methods: {
        // 获取轮播图数据
        fetchBannerData() {
            this.loading = true;
            this.searchParams.page = this.currentPage;
            this.searchParams.pageSize = this.pageSize;

            request
                .get("/admin/banner/pageSearch", { params: this.searchParams })
                .then((response) => {
                    if (response && response.code === 1) {
                        this.bannerList = response.data.records || [];
                        this.total = response.data.total || 0;
                    } else {
                        this.$message.error("获取轮播图数据失败：" + data.message);
                    }
                })
                .catch((error) => {
                    console.error("获取轮播图数据失败：", error);
                    this.$message.error("获取轮播图数据失败：" + error.message);
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        // 每页显示记录数改变时的处理
        handleSizeChange(newSize) {
            this.pageSize = newSize;
            this.fetchBannerData(); // 重新获取数据
        },
        // 当前页码改变时的处理
        handleCurrentChange(newPage) {
            this.currentPage = newPage;
            this.fetchBannerData(); // 重新获取数据
        },
        // 新增轮播图
        handleAdd() {
            this.addForm = {
                title: "",
                url: "",
                file: null,
            };
            this.fileList = [];
            this.addDialogVisible = true;
        },
        // 提交新增
        submitAdd() {
            this.$refs.addForm.validate((valid) => {
                if (valid) {
                    // 确保图片已经上传成功
                    if (!this.addForm.url) {
                        this.$message.error("请先上传图片");
                        return;
                    }

                    request
                        .post("/admin/banner/create", {
                            title: this.addForm.title,
                            url: this.addForm.url,
                        })
                        .then((response) => {
                            if (response && response.code === 1) {
                                this.$message.success("轮播图新增成功");
                                this.addDialogVisible = false;
                                this.fetchBannerData(); // 刷新列表
                            } else {
                                this.$message.error("轮播图新增失败：" + response.message);
                            }
                        })
                        .catch((error) => {
                            console.error("轮播图新增失败：", error);
                            this.$message.error("轮播图新增失败：" + error.message);
                        });
                } else {
                    this.$message.error("表单验证失败，请检查输入");
                }
            });
        },
        // 编辑轮播图
        handleEdit(row) {
            this.editForm = { ...row };
            this.fileList = row.url ? [{ name: row.title, url: row.url }] : [];
            this.editDialogVisible = true;
        },
        // 提交编辑
        submitEdit() {
            this.$refs.editForm.validate((valid) => {
                if (valid) {
                    // 如果用户重新上传了图片，更新图片地址
                    if (this.editForm.file) {
                        this.$axios
                            .post("/admin/common/upload", this.editForm.file)
                            .then((response) => {
                                const data = response.data;
                                if (data && data.code === 200) {
                                    this.editForm.url = response.data.url; // 获取上传后的图片路径
                                    this.updateBanner();
                                } else {
                                    this.$message.error("图片上传失败：" + data.message);
                                }
                            })
                            .catch((error) => {
                                console.error("图片上传失败：", error);
                                this.$message.error("图片上传失败：" + error.message);
                            });
                    } else {
                        this.updateBanner();
                    }
                } else {
                    this.$message.error("表单验证失败，请检查输入");
                }
            });
        },
        // 更新轮播图信息
        updateBanner() {
            console.log(this.editForm)
            request
                .post("/admin/banner/update", {
                    id: this.editForm.id,
                    title: this.editForm.title,
                    url: this.editForm.url,
                })
                .then((response) => {
                    if (response && response.code === 1) {
                        this.$message.success("轮播图更新成功");
                        this.editDialogVisible = false;
                        this.fetchBannerData(); // 刷新列表
                    } else {
                        this.$message.error("轮播图更新失败：" + response.message);
                    }
                })
                .catch((error) => {
                    console.error("轮播图更新失败：", error);
                    this.$message.error("轮播图更新失败：" + error.message);
                });
        },
        // 编辑时文件上传成功
        handleEditUploadSuccess(response, file) {
            if (response && response.code === 1) {
                console.log(response.data)
                this.editForm.url = response.data; // 获取上传后的图片路径
                this.$message.success("图片上传成功");
                console.log(this.editForm)
            } else {
                this.$message.error("图片上传失败：" + response.message);
            }
        },
        // 文件上传成功
        handleUploadSuccess(response, file) {
            if (response && response.code === 1) {
                console.log(response.data)
                this.addForm.url = response.data; // 获取上传后的图片路径
                this.addForm.file = file; // 保存文件对象
                this.$message.success("图片上传成功");
                console.log(this.addForm)
            } else {
                this.$message.error("图片上传失败：" + response.message);
            }
        },
        // 文件上传失败
        handleUploadError(err, file) {
            this.$message.error("图片上传失败：" + err.message);
        },
        // 文件上传前的校验
        beforeUpload(file) {
            const isImage = file.type.startsWith("image/");
            if (!isImage) {
                this.$message.error("只能上传图片文件");
                return false;
            }
            return true;
        },
        // 文件超出限制
        handleExceed() {
            this.$message.warning("只能上传一张图片");
        },
        // 文件移除
        handleRemove(file, fileList) {
            this.fileList = fileList;
        },
        // 删除轮播图
        handleDelete(row) {
            this.$confirm("此操作将永久删除该轮播图, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    request
                        .delete("/admin/banner/delete", { params: { id: row.id } })
                        .then((response) => {
                            if (response && response.code === 1) {
                                this.$message.success("轮播图删除成功");
                                this.fetchBannerData(); // 刷新列表
                            } else {
                                this.$message.error("轮播图删除失败：" + response.message);
                            }
                        })
                        .catch((error) => {
                            console.error("轮播图删除失败：", error);
                            this.$message.error("轮播图删除失败：" + error.message);
                        });
                })
                .catch(() => {
                    this.$message.info("已取消删除");
                });
        },
    },
};
</script>

<style scoped>
.banner-list-container {
    padding: 20px;
}

.search-form {
    margin-bottom: 20px;
}

.delete-btn {
    color: #f56c6c;
}
</style>